package com.tan.websocket.config;

import cn.hutool.http.HttpUtil;
import com.tan.core.constants.CommonConstants;
import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@ChannelHandler.Sharable
public class WebsocketAuthHandler extends ChannelInboundHandlerAdapter {

    public static Map<String, Channel> channelMap = new HashMap<>();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof FullHttpRequest request)) {
            ctx.fireChannelRead(msg);
            return;
        }
        String uri = request.uri();
        Map<String,String> params = HttpUtil.decodeParamMap(uri, StandardCharsets.UTF_8);
        String token = params.get(CommonConstants.AUTHORIZATION);
        if (StringUtil.isNullOrEmpty(token)) {
            log.info("token校验失败 关闭连接================");
            ctx.close().sync();
            return;
        }
        channelMap.put(token, ctx.channel());
        log.info("token校验成功：：{}================", token);
        ctx.fireChannelRead(msg);
    }
}

